package com.spic.business.informatization.before_after_work.service.impl;

import com.spic.business.common.datascope.anotation.BusinessDataScope;
import com.spic.business.datamanagement.meetingbefore.domain.MeetingBeforeAfterDirty;
import com.spic.business.datamanagement.meetingbefore.mapper.MeetingBeforeAfterDirtyMapper;
import com.spic.business.informatization.before_after_work.domain.MeetingBeforWorkSearchRecord;
import com.spic.business.informatization.before_after_work.domain.MeetingBeforeAfter;
import com.spic.business.informatization.before_after_work.mapper.MeetingBeforWorkSearchRecordMapper;
import com.spic.business.informatization.before_after_work.mapper.MeetingBeforeAfterMapper;
import com.spic.business.informatization.before_after_work.service.AsyncService;
import com.spic.business.informatization.before_after_work.service.IMeetingBeforeAfterService;
import com.spic.business.two.tickets.general.domain.AddSafetyPrecautionsSubtable;
import com.spic.business.two.tickets.general.domain.RiskControlMeasuresSubtable;
import com.spic.business.two.tickets.general.domain.SafetyPrecautionsSubtable;
import com.spic.business.two.tickets.general.eum.TableCategoryEnum;
import com.spic.business.two.tickets.general.mapper.AddSafetyPrecautionsSubtableMapper;
import com.spic.business.two.tickets.general.mapper.RiskControlMeasuresSubtableMapper;
import com.spic.business.two.tickets.general.mapper.SafetyPrecautionsSubtableMapper;
import com.spic.business.utils.GroupUtils;
import com.spic.business.violation.supervision.information.domain.ViolationInformation;
import com.spic.business.violation.supervision.information.domain.ViolationInformationDirty;
import com.spic.common.core.text.UUID;
import com.spic.common.core.utils.SecurityUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.common.core.utils.bean.BeanUtils;
import com.spic.common.core.web.domain.AjaxResult;
import com.spic.common.security.utils.cache.DeptCacheUtils;
import com.spic.system.api.dto.DeptDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 班前班后会主Service业务层处理
 *
 * @author yangjie
 * @date 2021-12-20
 */
@Service
public class MeetingBeforeAfterServiceImpl implements IMeetingBeforeAfterService
{
    @Autowired
    private MeetingBeforeAfterMapper meetingBeforeAfterMapper;

    @Autowired
    private RiskControlMeasuresSubtableMapper riskControlMeasuresSubtableMapper;

    @Autowired
    private SafetyPrecautionsSubtableMapper safetyPrecautionsSubtableMapper;

    @Autowired
    private AddSafetyPrecautionsSubtableMapper addSafetyPrecautionsSubtableMapper;
    @Autowired
    private MeetingBeforWorkSearchRecordMapper meetingBeforWorkSearchRecordMapper;
    @Autowired
    private ThreadPoolExecutor execute;
    @Autowired
    private MeetingBeforeAfterDirtyMapper meetingBeforeAfterDirtyMapper;
    //子表关联类别
    public static final String CATEGORY_NAME = TableCategoryEnum.MEETINGWORK.getCode();
    public static final String BEFOR_WORK_NAME = TableCategoryEnum.MEETINGWORK.getDesc();
    @Autowired
    private AsyncService asyncService;

    private String minioUrl = "http://111.202.164.187:9000";
    //private String minioUrl = "http://62.234.4.59:9000";

    /**
     * 查询班前班后会主
     *
     * @param id 班前班后会主主键
     * @return 班前班后会主
     */
    @Override
    public MeetingBeforeAfter selectMeetingBeforeAfterById(String id)
    {
        MeetingBeforeAfter meetingBeforeAfter = meetingBeforeAfterMapper.selectMeetingBeforeAfterById(id, CATEGORY_NAME);
        return meetingBeforeAfter;
    }

    /**
     * 查询班前班后会主列表
     *
     * @param meetingBeforeAfter 班前班后会主
     * @return 班前班后会主
     */
    @BusinessDataScope(menuPath = "business/informatization/beforeAfterWork/index")
    @Override
    public List<MeetingBeforeAfter> selectMeetingBeforeAfterList(MeetingBeforeAfter meetingBeforeAfter)
    {
        return meetingBeforeAfterMapper.selectMeetingBeforeAfterList(meetingBeforeAfter);
    }

    /**
     * 新增班前班后会主
     *
     * @param meetingBeforeAfter 班前班后会主
     * @return 结果
     */
    @Override
    public AjaxResult insertMeetingBeforeAfter(MeetingBeforeAfter meetingBeforeAfter)
    {
        MeetingBeforeAfter meetingBefor = meetingBeforeAfterMapper.selectMeetingBeforeAfterByMeetingName(meetingBeforeAfter.getMeetingName());
       if(meetingBefor!=null){
           return AjaxResult.error("会议名称已存在,请确认会议日期！");
       }
        //前端生成ID
//        String id = UUID.randomUUID().toString().replaceAll("-", "");
//        meetingBeforeAfter.setId(id);
        int rows =  meetingBeforeAfterMapper.insertMeetingBeforeAfter(meetingBeforeAfter);
        if(rows>0)
        {
            //if(meetingBeforeAfter.getKeyworkFile() !=null && StringUtil.isEmpty(meetingBeforeAfter.getVedioResult()) ){
            if(meetingBeforeAfter.getKeyworkFile() !=null){
                String obsUrl = minioUrl+meetingBeforeAfter.getKeyworkFile().split("\\|")[0];
                //String obsUrl = "http://8.218.45.242:8090/static/img/test.mp3";
                asyncService.getVedioText(obsUrl,meetingBeforeAfter.getId());
            }
        }

        //新增会议地点 搜索框历史
        insertMeetingBeforeSearch(meetingBeforeAfter);
        insertSafetyPrecautionsSubtable(meetingBeforeAfter);
        return AjaxResult.success("创建成功");
    }

    private void insertMeetingBeforeSearch(MeetingBeforeAfter meetingBeforeAfter)
    {
        String meetingPlace = meetingBeforeAfter.getMeetingPlace();
        Long deptId = meetingBeforeAfter.getDeptId();
        if(StringUtils.isNotEmpty(meetingPlace)){
            MeetingBeforWorkSearchRecord meetingBeforWorkSearchRecord = meetingBeforWorkSearchRecordMapper.selectMeetingBeforWorkSearchRecordByName(meetingPlace, deptId);
            if(meetingBeforWorkSearchRecord==null)
            {
                MeetingBeforWorkSearchRecord searchRecord = new MeetingBeforWorkSearchRecord();
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                searchRecord.setId(uuid);
                searchRecord.setDeptId(deptId);
                searchRecord.setType("1");
                searchRecord.setContent(meetingPlace);
                meetingBeforWorkSearchRecordMapper.insertMeetingBeforWorkSearchRecord(searchRecord);
            }
        }
    }
    /**
     * 修改班前班后会主
     *
     * @param meetingBeforeAfter 班前班后会主
     * @return 结果
     */
    @Override
    public int updateMeetingBeforeAfter(MeetingBeforeAfter meetingBeforeAfter)
    {
        safetyPrecautionsSubtableMapper.deleteSafetyPrecautionsSubtableByParentId(meetingBeforeAfter.getId(), CATEGORY_NAME);
        riskControlMeasuresSubtableMapper.deleteRiskControlMeasuresSubtableByParentId(meetingBeforeAfter.getId(), CATEGORY_NAME);
        addSafetyPrecautionsSubtableMapper.deleteAddSafetyPrecautionsSubtableByParentId(meetingBeforeAfter.getId(), CATEGORY_NAME);
        //新增会议地点 搜索框历史
        insertMeetingBeforeSearch(meetingBeforeAfter);
        insertSafetyPrecautionsSubtable(meetingBeforeAfter);

        if(meetingBeforeAfter.getKeyworkFile() !=null){
            String obsUrl = minioUrl+meetingBeforeAfter.getKeyworkFile().split("\\|")[0];
            //String obsUrl = "http://8.218.45.242:8090/static/img/test.mp3";
            asyncService.getVedioText(obsUrl,meetingBeforeAfter.getId());
        }
        return meetingBeforeAfterMapper.updateMeetingBeforeAfter(meetingBeforeAfter);
    }

    /**
     * 批量删除班前班后会主
     *
     * @param ids 需要删除的班前班后会主主键
     * @return 结果
     */
    @Override
    public int deleteMeetingBeforeAfterByIds(String[] ids)
    {
        safetyPrecautionsSubtableMapper.deleteSafetyPrecautionsSubtableByParentIds(ids, CATEGORY_NAME);
        addSafetyPrecautionsSubtableMapper.deleteAddSafetyPrecautionsSubtableByParentIds(ids, CATEGORY_NAME);
        riskControlMeasuresSubtableMapper.deleteRiskControlMeasuresSubtableByParentIds(ids, CATEGORY_NAME);
        return meetingBeforeAfterMapper.deleteMeetingBeforeAfterByIds(ids);
    }

    /**
     * 删除班前班后会主信息
     *
     * @param id 班前班后会主主键
     * @return 结果
     */
    @Override
    public int deleteMeetingBeforeAfterById(String id)
    {
        safetyPrecautionsSubtableMapper.deleteSafetyPrecautionsSubtableByParentId(id, CATEGORY_NAME);
        riskControlMeasuresSubtableMapper.deleteRiskControlMeasuresSubtableByParentId(id, CATEGORY_NAME);
        addSafetyPrecautionsSubtableMapper.deleteAddSafetyPrecautionsSubtableByParentId(id, CATEGORY_NAME);
        return meetingBeforeAfterMapper.deleteMeetingBeforeAfterById(id);
    }

    @Override
    public String selectMeetingBeforWorkCode()
    {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        String code = "";
        Long userId = SecurityUtils.getUserId();
        String deptId = SecurityUtils.getDeptId()+"";
        List<DeptDTO> cache = DeptCacheUtils.getCache();
        for (DeptDTO deptDTO : cache)
        {
            Long deptId1 = deptDTO.getDeptId();
            Long parentId = deptDTO.getParentId();
            if(deptId.equals(deptId1+"")){
                try
                {
                    if(parentId!=null){
                        String value = DeptCacheUtils.getValue(parentId);
                        code+=value+"/"+deptDTO.getDeptName()+"-"+sd.format(new Date())+"-"+BEFOR_WORK_NAME;
                    }
                } catch (Exception e)
                {
                    e.printStackTrace();
                }

            }else{
                continue;
//                 code = deptDTO.getDeptName()+deptDTO.getDeptName()+ sd.format(new Date());
            }
        }
        return code;
    }

    @Override
    public MeetingBeforeAfter getMeetingBeforWorkByMeetingName()
    {
        String meetingName = this.selectMeetingBeforWorkCode();
        return meetingBeforeAfterMapper.selectMeetingBeforeAfterByMeetingName(meetingName);
    }

    /**
     * 新增安全措施子数据信息
     *
     * @param meetingBeforeAfter 电气第二种工作票单对象
     */
    public void insertSafetyPrecautionsSubtable(MeetingBeforeAfter meetingBeforeAfter)
    {
        List<SafetyPrecautionsSubtable> safetyPrecautionsSubtableList = meetingBeforeAfter.getSafetyPrecautionsSubtableList();
        List<AddSafetyPrecautionsSubtable> addSafetyPrecautionsSubtableList = meetingBeforeAfter.getAddSafetyPrecautionsSubtableList();
        List<RiskControlMeasuresSubtable> riskControlMeasuresSubtableList = meetingBeforeAfter.getRiskControlMeasuresSubtableList();

        String id = meetingBeforeAfter.getId();
        if (StringUtils.isNotNull(safetyPrecautionsSubtableList))
        {
            List<SafetyPrecautionsSubtable> list = new ArrayList<SafetyPrecautionsSubtable>();
            for (SafetyPrecautionsSubtable safetyPrecautionsSubtable : safetyPrecautionsSubtableList)
            {
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                safetyPrecautionsSubtable.setTableName(CATEGORY_NAME);
                safetyPrecautionsSubtable.setParentId(id);
                safetyPrecautionsSubtable.setId(uuid);
                list.add(safetyPrecautionsSubtable);
            }
            if (list.size() > 0)
            {
                safetyPrecautionsSubtableMapper.batchSafetyPrecautionsSubtable(list);
            }
        }
        if (StringUtils.isNotNull(addSafetyPrecautionsSubtableList))
        {
            List<AddSafetyPrecautionsSubtable> list = new ArrayList<AddSafetyPrecautionsSubtable>();
            for (AddSafetyPrecautionsSubtable addSafetyPrecautionsSubtable : addSafetyPrecautionsSubtableList)
            {
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                addSafetyPrecautionsSubtable.setTableName(CATEGORY_NAME);
                addSafetyPrecautionsSubtable.setParentId(id);
                addSafetyPrecautionsSubtable.setId(uuid);
                list.add(addSafetyPrecautionsSubtable);

            }
            if (list.size() > 0)
            {
                addSafetyPrecautionsSubtableMapper.batchAddSafetyPrecautionsSubtable(list);
            }
        }
        if (StringUtils.isNotNull(riskControlMeasuresSubtableList))
        {
            List<RiskControlMeasuresSubtable> list = new ArrayList<RiskControlMeasuresSubtable>();
            for (RiskControlMeasuresSubtable riskControlMeasuresSubtable : riskControlMeasuresSubtableList)
            {
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                riskControlMeasuresSubtable.setTableName(CATEGORY_NAME);
                riskControlMeasuresSubtable.setParentId(id);
                riskControlMeasuresSubtable.setId(uuid);
                list.add(riskControlMeasuresSubtable);
            }
            if (list.size() > 0)
            {
                riskControlMeasuresSubtableMapper.batchRiskControlMeasuresSubtable(list);
            }
        }
    }

    @Override
    public void filterDirtyData() {
        meetingBeforeAfterDirtyMapper.delete(null);
        List<MeetingBeforeAfter> list = meetingBeforeAfterMapper.selectMeetingBeforeAfterList(new MeetingBeforeAfter());
        //计算需要的线程数 , 假定一个线程处理 500条数据吧
        List<List<MeetingBeforeAfter>> lists = GroupUtils.groupData(list, 500);
        for (List<MeetingBeforeAfter> subList : lists) {
            execute.execute(() -> {
                for(MeetingBeforeAfter meetingBeforeAfter : subList) {
                    if(meetingBeforeAfter.getTeamNumber() /2 > meetingBeforeAfter.getAttendanceNumber()) {
                        MeetingBeforeAfterDirty meetingBeforeAfterDirty = new MeetingBeforeAfterDirty();
                        meetingBeforeAfterDirty.setDirtyReason("出勤人数不足一半");
                        BeanUtils.copyBeanProp(meetingBeforeAfterDirty, meetingBeforeAfter);
                        meetingBeforeAfterDirtyMapper.insertMeetingBeforeAfterDirty(meetingBeforeAfterDirty);
                    }
                }
            });
        }
    }
}
